import 'dart:async';

import 'package:data/response/project_response.dart';
import 'package:dio/dio.dart';
import 'package:util/result/catching.dart';
import 'package:util/result/result_extension.dart';

abstract class ProjectsRepository {
  Future<ProjectResponse> fetchProjects({
    required int pageIndex,
    required int categoryId,
  });
}

class ProjectsRepositoryImpl implements ProjectsRepository {
  final Dio _dio;

  const ProjectsRepositoryImpl({required Dio dio}) : _dio = dio;

  @override
  Future<ProjectResponse> fetchProjects({
    required int pageIndex,
    required int categoryId,
  }) async {
    final apiResult = await runCatchingAsync(() async {
      final url =
          "https://www.wanandroid.com/project/list/$pageIndex/json?cid=$categoryId";
      final result = await _dio.get(url);
      final data = result.data['data'];
      final projectList = (data['datas'] as List<dynamic>)
          .map((json) => Project.fromJson(json))
          .toList();
      return ProjectResponse(total: data['total'], projects: projectList);
    });

    return apiResult.getOrNull() ?? ProjectResponse(total: 0, projects: []);
  }
}
